package com.starsoft.frame.base.web;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.starsoft.frame.base.bean.BaseAcount;
import com.starsoft.frame.base.bean.BaseUser;
import com.starsoft.frame.base.bean.UserContext;
import com.starsoft.frame.base.plugin.AcountPluginService;
import com.starsoft.frame.base.service.AcountService;
import com.starsoft.frame.base.service.UserService;
import com.starsoft.frame.core.orm.PageObject;
import com.starsoft.frame.core.web.WebUtil;

@RestController
@RequestMapping(value = "/base/acount")
public class BaseAcountController {

	@Autowired
	AcountService acountService;
	
	@Autowired
	UserService userService;
	
	@Autowired
	AcountPluginService acountPluginService;
	
	
	@RequestMapping("/pageparent")
	public Map<String, Object> pageParent(ServletRequest request){
		PageObject po = WebUtil.getPageObject(request);
		UserContext context = UserService.getUserContext();
		return acountService.pageParentAcount(context.getUser(), po);
	}
	
	@RequestMapping("/allparent")
	public Map<String, Object> getAllParent(){
		UserContext context = UserService.getUserContext();
		Map<String, Object> model = new HashMap<>();
		model.put("acounts", acountService.getParentAcount(context.getUserId()));
		model.put("acount", context.getAcount());
		return model;
	}
	
	@RequestMapping("/allsun")
	public List<BaseAcount> getAllSun(BaseAcount acount){
		return acountService.getSunAcount(acount);
	}
	
	@RequestMapping("/allacount")
	public List<BaseAcount> getAllAcount(ServletRequest request){
		UserContext context = UserService.getUserContext();
		return acountService.getAcount(context.getUser());
	}
	
	@RequestMapping("/save")
	public Map<String, Object> saveAcount(BaseAcount acount){
		UserContext context = UserService.getUserContext();
		acount.setUserId(context.getUserId());
		acountService.saveAcount(acount);
		userService.updateUserContext();
		return WebUtil.sucesseModel("保存成功");
	}
	
	@RequestMapping("/delete")
	public Map<String, Object> deleteAcount(BaseAcount acount){
		acountService.checkCanRemove(acount);
		acountPluginService.delete(acount);
		userService.updateUserContext();
		return WebUtil.sucesseModel("删除成功");
	}
	
	@RequestMapping(value = "/copyacount")
	public Map<String, Object> copyAcount(BaseAcount acount){
		BaseAcount sunAcount = acountPluginService.copyAsSun(acount, null);
		return WebUtil.sucesseModel("Copy成功，"+ sunAcount.getAcountName());
	}

	@RequestMapping(value = "/synchgroup")
	public Map<String, Object> synchGroup(BaseAcount acount){
		acountPluginService.updateSunAcounts(acount);
		return WebUtil.sucesseModel("同步成功");
	}

}
